<script setup>
import {ref} from 'vue'

import {onMounted} from "vue";

import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {ElMessage, ElMessageBox} from "element-plus";

import {
  addTodoService,
  todoListService,
  completeTodoService,
  deleteTodoService,
  updateTodoService
}
  from "@/api/todo.js";
import {Delete, Edit} from "@element-plus/icons-vue";

// 抽屉显示
const visibleDrawer = ref(false)
// 抽屉标题
const drawerTitle = ref()
// 待办事项模型
const todoItemModel = ref()
// 待办事项列表
const todoList = ref()

// 分页参数
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref()

onMounted(() => {
  clearTodoItemModel()
  getTodoList()
})

// 清空todoItemModel
const clearTodoItemModel = () => {
  todoItemModel.value = {
    title: '',
    description: '',
    dueTime: '',
    status: ''
  }
}

// 调用分页查询
const getTodoList = async () => {
  let result = await todoListService({
    pageNum: pageNum.value,
    pageSize: pageSize.value
  })
  total.value = result.data.total
  todoList.value = result.data.items
}

// 添加-rule
const addRules = {
  title: [
    {required: true, message: 'input a title', trigger: "blur"},
    {pattern: /^\s*\S.{0,39}\S\s*$/, message: "1-40 character", trigger: 'blur'}
  ],
  description: [{required: true, message: 'input the description', trigger: 'blur'}],
  dueTime: [{type: 'date', required: true, message: 'choose the due time', trigger: 'change'}]
}

// 添加待办事项函数
const addTodoItem = async () => {
  todoItemModel.value.status = 'TODO'
  let result = await addTodoService(todoItemModel.value)

  ElMessage.success(result.message ? result.message : "login success")

  // 关闭抽屉
  visibleDrawer.value = false
  // 清空model
  clearTodoItemModel()
  // 重新加载待办事项列表
  await getTodoList()
}

// 完成
const completeItem = async (id) => {
  let result = await completeTodoService(id)
  ElMessage.success(result.message ? result.message : "change success")

  await getTodoList()
}

// 修改
const updateItem = (item) => {
  // 抽屉赋值
  drawerTitle.value = 'Update TodoItem'
  visibleDrawer.value = true
  // 初始化抽屉值
  todoItemModel.value = {
    todoId: item.todoId,
    title: item.title,
    description: item.description,
    dueTime: item.dueTime,
    status: item.status
  }
}

const updateTodoItem = async () => {
  let result = await updateTodoService(todoItemModel.value)

  ElMessage.success(result.message ? result.message : 'update success')
  // 隐藏抽屉
  visibleDrawer.value = false

  await getTodoList()
}

// 删除
const removeItem = (id) => {
  ElMessageBox.confirm('确认要删除吗？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let result = await deleteTodoService(id)
    ElMessage.success(result.message ? result.message : 'delete success')

    await getTodoList()
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <el-row justify="space-between">
          <span>TODO LIST</span>
          <div class="extra">
            <el-button type="primary" @click="visibleDrawer = true;drawerTitle = 'Add TodoItem'">ADD</el-button>
          </div>
        </el-row>
      </div>
    </template>
    <!--  待办事项展示  -->
    <div v-for="item in todoList">
      <el-card class="box-card">
        <template #header>
          <el-row class="card-header" justify="space-between">
            <el-col :span="8">
              <div class="item-title"><strong>Title: {{ item.title }}</strong></div>
            </el-col>
            <el-col :span="4">
              <el-button v-if="item.status === 'TODO'" type="success" size="small" round
                         @click="completeItem(item.todoId)">Transfer to DONE
              </el-button>
              <el-button v-else-if="item.status === 'DONE'" type="info" size="small" round disabled>DONE</el-button>
              <el-button @click="updateItem(item)" type="primary" size="small" :icon="Edit" circle/>
              <el-button @click="removeItem(item.todoId)" type="danger" size="small" :icon="Delete" circle/>
            </el-col>
          </el-row>
        </template>
        <div class="text item">Description: {{ item.description }}</div>
        <template #footer>Due Date: {{ item.dueDate }}</template>
      </el-card>
      <br>
    </div>
    <!--  抽屉  -->
    <el-drawer v-model="visibleDrawer" :title="drawerTitle" direction="rtl" size="50%">
      <!-- 添加待办事项表单 -->
      <el-form :label-position="'left'" :model="todoItemModel" label-width="100px" :rules="addRules">
        <!--标题-->
        <el-form-item label="Title" prop="title">
          <el-input v-model="todoItemModel.title" placeholder="Input a title"></el-input>
        </el-form-item>
        <!--描述-->
        <el-form-item label="Description" prop="description">
          <div class="editor">
            <quill-editor theme="snow" v-model:content="todoItemModel.description" contentType="html">
            </quill-editor>
          </div>
        </el-form-item>
        <!--预期时间-->
        <el-form-item label="DueDate" prop="dueTime">
          <el-col :span="24">
            <el-date-picker
                v-model="todoItemModel.dueTime"
                type="date"
                placeholder="Pick a due date"
                style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button v-if="drawerTitle.toString().startsWith('Add')" type="primary" @click="addTodoItem()">Add
          </el-button>
          <el-button v-else-if="drawerTitle.toString().startsWith('Update')" type="primary" @click="updateTodoItem()">
            Update
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!--  分页  -->
    <template #footer>
      <el-pagination background layout="prev, pager, next, jumper, total" :total="total"
                     v-model:current-page="pageNum" v-model:page-size="pageSize"
                     @current-change="val => {pageNum = val; getTodoList()}"/>
    </template>
  </el-card>
</template>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;
}

/* 抽屉样式 */
.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>